using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;

namespace RaisingStudio.SmallBasicCompiler.Expressions
{
	[Serializable]
	public class MethodCallExpression : Expression
	{
		private List<Expression> _arguments = new List<Expression>();
		public TokenInfo TypeName
		{
			get;
			set;
		}
		public TokenInfo MethodName
		{
			get;
			set;
		}
		public List<Expression> Arguments
		{
			get
			{
				return this._arguments;
			}
		}
		public override void AddSymbols(SymbolTable symbolTable)
		{
			foreach (Expression current in this.Arguments)
			{
				current.AddSymbols(symbolTable);
			}
		}
		public override void EmitIL(CodeGenScope scope)
		{
			MethodInfo methodInfo = this.GetMethodInfo(scope);
			foreach (Expression current in this.Arguments)
			{
				current.EmitIL(scope);
			}
			scope.ILGenerator.EmitCall(OpCodes.Call, methodInfo, null);
		}
		public MethodInfo GetMethodInfo(CodeGenScope scope)
		{
			TypeInfo typeInfo = scope.TypeInfoBag.Types[this.TypeName.NormalizedText];
			return typeInfo.Methods[this.MethodName.NormalizedText];
		}
		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendFormat(CultureInfo.CurrentUICulture, "{0}.{1}(", new object[]
			{
				this.TypeName.Text, 
				this.MethodName.Text
			});
			if (this.Arguments.Count > 0)
			{
				foreach (Expression current in this.Arguments)
				{
					stringBuilder.AppendFormat(CultureInfo.CurrentUICulture, "{0}, ", new object[]
					{
						current
					});
				}
				stringBuilder.Remove(stringBuilder.Length - 2, 2);
			}
			stringBuilder.Append(")");
			return stringBuilder.ToString();
		}
	}
}
